<template>
  <div class="banding-prediction" :loading="loading">
    <el-collapse v-model="activeNames" :before-collapse="beforeCollapse">
      <template v-for="(item, index) in infoList" :key="index">
        <el-collapse-item :title="item.tsidDay" :name="index">
          <template #icon="{ isActive }">
            <template v-if="showAll != 'today'">
              <span class="icon-ele">
                {{ isActive ? '收起' : '展开' }}
              </span>
              <el-icon v-if="isActive"><ArrowUpBold /></el-icon>
              <el-icon v-else><ArrowDownBold /></el-icon>
            </template>
            <span v-else> </span>
          </template>
          <div class="detai-table">
            <BasicVxeTable
              ref="gridRefDoff"
              stripe
              :data="item.tsidList"
              :columns="columns"
              :merge-cells="[
                { row: 0, col: 0, rowspan: item.dayShiftNum, colspan: 1 },
                { row: item.dayShiftNum, col: 0, rowspan: item.nightShiftNum, colspan: 1 }
              ]"
            >
              <template #state="{ row }">
                <el-tag effect="dark" :color="zhuanTai.color(Number(row.stateCode))">
                  {{ zhuanTai.text(Number(row.stateCode), '细纱') }}
                </el-tag>
              </template>
            </BasicVxeTable>
          </div>
        </el-collapse-item>
      </template>
    </el-collapse>
  </div>
</template>

<script setup lang="ts">
  import { getXiShaFenBanHuaDuan } from '@/api/shengChanJianShi'
  import { splitTsIdToTime, zhuanTai } from '@/utils/custom/index'
  import dayjs from 'dayjs'

  const props = defineProps({
    showAll: {
      type: String,
      default: 'all'
    }
  })

  const beforeCollapse = () => {
    return props.showAll != 'today' ? true : false
  }

  const emits = defineEmits(['updateStr'])
  const loading = ref(false)
  const activeNames = ref<any>([])
  const infoList = ref()
  const getInfoList = () => {
    loading.value = true
    getXiShaFenBanHuaDuan()
      .then((res: any) => {
        loading.value = false
        let temp = res.rovingRenewPrediction.map((value, index: number) => {
          activeNames.value.push(index)
          value.tsidDay = splitTsIdToTime(value.tsidDay)
          value.dayShiftNum = value.byTsid.find((val) => val.shiftNum == 1)?.detail.length || 0
          value.nightShiftNum = value.byTsid.find((val) => val.shiftNum == 2)?.detail.length || 0
          value.tsidList = []
          for (let i = 0; i < value.byTsid.length; i++) {
            const element = value.byTsid[i]
            for (let j = 0; j < element.detail.length; j++) {
              value.tsidList.push({
                ...element.detail[j],
                classes: element.shiftNum === 1 ? '白班' : '夜班',
                predictionChangeTimeNext: dayjs(element.detail[j].predictionChangeTimeNext).format(
                  'YYYY-MM-DD HH:mm'
                )
              })
            }
          }

          return value
        })

        if (props.showAll === 'today') {
          infoList.value = [temp[0]]
          handleSegmentSr(temp)
        } else {
          infoList.value = temp
        }
      })
      .catch(() => {
        loading.value = false
      })
  }

  const handleSegmentSr = (arr) => {
    // 处理数据  获取粗细联工序-综合报表-今日细纱换段需求 右侧数据
    let result = ''

    // 扁平化嵌套数组 - 使用 flatMap
    const varietyArr = arr[0]?.byTsid?.flatMap((item) => item.detail) || []

    if (varietyArr.length > 0) {
      // 按 materialId 分组 - 使用 Map 和 reduce
      const groupedData = [
        ...varietyArr
          .reduce((map, item) => {
            const key = item.materialId
            const group = map.get(key) || {
              materialId: key,
              materialName: item.materialName,
              data: []
            }
            group.data.push(item)
            return map.set(key, group)
          }, new Map())
          .values()
      ]

      // 格式化结果字符串 - 使用模板字符串和 join
      result = groupedData
        .map((item) => `&emsp;&emsp;${item.materialName}:${item.data.length * 8}挂;`)
        .join('')
    }

    emits('updateStr', result)
  }

  const columns: BasicGridColumnProps[] = [
    {
      title: '班次',
      field: 'classes',
      align: 'center',
      width: 120
    },
    {
      title: '机台号',
      field: 'machineName',
      align: 'center',
      width: 140
    },
    {
      title: '状态',
      field: 'stateCode',
      slots: { default: 'state' },
      align: 'center'
    },
    {
      title: '品种',
      field: 'materialName',
      align: 'center'
    },
    {
      title: '预计下次换段时间',
      field: 'predictionChangeTimeNext',
      align: 'center'
    },
    {
      title: '初始长度',
      field: 'fixLengthCs',
      align: 'center'
    },
    {
      title: '粗纱剩余长度',
      field: 'currentLengthCs',
      align: 'center'
    }
  ]

  onMounted(() => {
    getInfoList()
  })

  defineExpose({
    getInfoList
  })
</script>
<style scoped lang="scss">
  :deep(.el-collapse-item__header) {
    background: #78be20;
    color: #fff;
    padding: 0 12px;
    height: 31px;
  }

  :deep(.el-collapse-item__wrap) {
    border-bottom: none;
    .el-collapse-item__content {
      padding-bottom: 0;
    }
  }

  .detai-table {
    padding-bottom: 20px;
  }

  .banding-prediction {
    height: 100%;
  }
</style>
